package server.controller.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.ShopCarDao;
import server.dao.ShopDao;
import server.dao.UsersDao;
import server.model.entity.Shop;
import server.model.entity.ShopCar;
import server.model.entity.Users;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v2/api/car")
@Api(value = "对外接口（购物车）", tags = {"需登录(购物车)"})
@CrossOrigin(origins = "*")
public class CarController {
    @Autowired
    ShopCarDao shopCarDao;
    @Autowired
    ShopDao shopDao;
    @Autowired
    UsersDao usersDao;

    @ApiOperation("加入购物车")
    @PostMapping("/{shopId}/{number}")
    public RetResult addShop(@PathVariable String shopId, @PathVariable Integer number) {
        Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        ShopCar sc = shopCarDao.findByUsers_IdAndShop_Id(users.getId(), shopId);
        Optional<Shop> sp = shopDao.findById(shopId);
        if (!sp.isPresent() || !sp.get().getStatus()) {
            return RetResponse.makeErrRsp("商品不存在或已下架!");
        }
        if (number <= 0 && sc==null) {
            return RetResponse.makeErrRsp("至少添加一件商品!");
        }
        if (number <= 0 && sc!=null) {
            shopCarDao.deleteById(sc.getId());
            return RetResponse.makeOKRsp();
        }
        if (sc == null) {
            ShopCar shopCar = new ShopCar();
            shopCar.setCount(number);
            shopCar.setShop(sp.get());
            shopCar.setUsers(usersDao.findById(users.getId()).get());
            shopCarDao.save(shopCar);
        } else {
            sc.setCount(number);
            shopCarDao.save(sc);
        }
        return RetResponse.makeOKRsp();
    }

    @ApiOperation("批量删除购物车")
    @DeleteMapping("/del")
    @Transactional
    public RetResult addShop(@RequestBody List<String> carIds) {
        shopCarDao.deleteByIdIn(carIds);
        return RetResponse.makeOKRsp();
    }

    @ApiOperation("我的购物车")
    @GetMapping()
    public RetResult getCarByUserId() {
        Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        return RetResponse.makeOKRsp(shopCarDao.findByUsers_Id(users.getId()));
    }
}
